const {AppletUser, WxAppletUser} = require('../db/seq')

class AppletUserServe {
    async createOrUpdateUserServe(nickName, avatar, openId) {
        try {
            const res = await AppletUser.findOrCreate({
                where: {
                    openId
                },
                defaults: {
                    nickName,
                    avatar
                }
            })
            return res;
        } catch (e) {
            console.log(e);
            throw ({message: e.message})
        }
    }

    async createWxUserServe(params) {
        try {
            const res = await WxAppletUser.create({
                ...params
            })
            return res;
        } catch (e) {
            console.log(e);
            throw ({message: e.message})
        }
    }

    async findWxUserByIdServe({openid, id}) {
        const whereOpt = {}
        openid && Object.assign(whereOpt, {
            openid
        });
        id && Object.assign(whereOpt, {
            id
        });
        try {
            const res = await WxAppletUser.findOne({
                where: whereOpt
            })
            console.log(res, '根据openId找到的用户');
            return res;
        } catch (e) {
            console.log(e);
            throw ({message: e.message})
        }
    }

    async updateWxUserTokenServe(token, id) {
        const res = await WxAppletUser.update({
            token
        }, {
            where: {
                id
            }
        })
        return res[0] > 0;
    }

}

module.exports = new AppletUserServe();
